package vip.xumy.admin.bmap.pojo;

import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Future;

import lombok.Getter;
import lombok.Setter;
import vip.xumy.admin.bmap.util.BMapTool;

/**
 * @author:mengyxu
 * @date:2021年10月26日
 */

@Setter
@Getter
public class WorkContext extends DownWorker {

	private long start;

	private Set<Future<?>> futures = new HashSet<>();
	private Future<?> submit;
	private Point leftBottom;
	private Point rightTop;

	public void setCityInfo(CityLocate city) {
		super.setCity(city.getId());
		super.setCityName(city.getName());
		this.leftBottom = new Point(city.getMinLng(), city.getMinLat());
		this.rightTop = new Point(city.getMaxLng(), city.getMaxLat());
		this.callTotal();
	}

	private void callTotal() {
		for (int z = minZom; z <= maxZom; z++) {
			leftBottom.setZ(z);
			rightTop.setZ(z);
			BMapTool.callXY(leftBottom);
			BMapTool.callXY(rightTop);
			total += ((rightTop.getX() - leftBottom.getX() + 1) * (rightTop.getY() - leftBottom.getY() + 1));
		}
	}

	public void addFuture(Future<?> future) {
		futures.add(future);
	}

	public void success() {
		super.success++;
	}

	public void fail() {
		super.fail++;
	}

	public void exist() {
		super.exist++;
	}

	public String status() {
		return MessageFormat.format("瓦片总数:{0},下载成功：{1},已存在：{2},下载失败：{3}", total, success, exist, fail);
	}

	public int getSize() {
		Iterator<Future<?>> iter = futures.iterator();
		while (iter.hasNext()) {
			Future<?> future = (Future<?>) iter.next();
			if (future.isDone() || future.isCancelled()) {
				iter.remove();
			}
		}
		return futures.size();
	}

	public boolean started() {
		return submit != null;
	}

	public boolean isDone() {
		if (submit == null) {
			return false;
		}
		return submit != null && submit.isDone() && getSize() == 0;
	}

	public long getUsed() {
		return System.currentTimeMillis() - start;

	}

	public long getUse() {
		int i = success + fail;
		if (i == 0) {
			return 0;
		}
		int l = total - i - exist;
		double x = l * 1.0 / i;
		long used = System.currentTimeMillis() - start;
		return (long) (used * x);
	}

}
